//录面板
var gridPanel;
//表单窗口
var contentPanel;
//单面板
var formPanel;
//页面布局管理器
var viewport = null;
//服务处理标志
var processFlag = false;

Date.prototype.toString=function(){ 
  return this.format("Ymd"); 
};

var configFormWindow;
var configFormPanel;
var uploadFormWindow;
var uploadFormPanel;

var recordDef = Ext.data.Record.create([{name:'code'},{name:'name'}]);
var dataStore = new Ext.data.Store({
	proxy:new Ext.data.HttpProxy({url:'/getAllEnviroments'}),
	reader:new Ext.data.JsonReader({id:'code',root:'comboBox'},recordDef),
	remoteStore:true
});
var dataStore1 = new Ext.data.Store({
	proxy:new Ext.data.HttpProxy({url:'/getAllEnviroments?excludeAll=true'}),
	reader:new Ext.data.JsonReader({id:'code',root:'comboBox'},recordDef),
	remoteStore:true
});
var projectDataStore = new Ext.data.Store({
	proxy:new Ext.data.HttpProxy({url:'/getApplications'}),
	reader:new Ext.data.JsonReader({id:'code',root:'comboBox'},recordDef),
	remoteStore:true
});

//格式化日期  
function formatDate(value) {  
    if (Ext.isEmpty(value)) {//判断是否是日期类型的数据  
        return '';  
    } else {  
        if (Ext.isDate(value)){  
        	alert("1  "+value+"  "+Ext.util.Format.date(value, 'Ymd'));
            return ""+Ext.util.Format.date(value, 'Ymd');// 用于时间控件返回值  
        }
        else  {  
        	alert("2  "+value+"  "+Ext.util.Format.date(new Date(value), 'Ymd'));
            return Ext.util.Format.date(new Date(value), 'Ymd');// 转换为Date类型  
        }
    }  
} 

//创建活动面板
function createGridPanel(){
	//检查对象是否已经创建
	if( gridPanel!=null ) return;
	//设置数据源
	var ds = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({url:systemContext + '/sysuser/page'}),
		reader: new Ext.data.JsonReader({
				root: 'records',
				totalProperty: 'total',
				id: 'id'
			},
			['id','userName','type','remark','createTime','updateTime']
		)
	});
	//列选择模式
	var sm = new Ext.grid.CheckboxSelectionModel();
	//列表名
	var colModel = new Ext.grid.ColumnModel([        
        new Ext.grid.RowNumberer({header:"序号",width:30}),
        sm,
        {header:"用户ID",dataIndex:"id",width:50},
        {header:"登录名",dataIndex:"userName",width:120,editor: new Ext.form.TextField({allowBlank: false})},
        {header:"用户类型",dataIndex:"type",width:100,renderer:function(value){
        	if( value=='A'){
        		return '超级用户';
        	}else {
        		return '普通用户';
        	}
        }},
        {header:"备注",dataIndex:"remark",width:160,editor: new Ext.form.TextField({allowBlank: false})},
        {header:"创建时间",dataIndex:"createTime",width:160},
        {header:"修改时间",dataIndex:"updateTime",width:160},
      ]);
	colModel.defaultSortable = true;
	//创建grid面板
	gridPanel = new Ext.grid.EditorGridPanel({
			border:false,
			buttonAlign :'left',
			loadMask: true,
			store: ds,
			autoExpandColumn:3,
			height:'100%',
			autoWidth:false,
			cm: colModel,
			sm: sm,
			autoScroll: true,
			tbar: [
				{xtype:'tbseparator'},
				'用户名：',{xtype:'textfield',width:80,id:'userName',name:'userName'},{xtype:'tbseparator'},
				{text:'搜索',iconCls:'icon-search',handler:function(){
					ds.load({
				    	params:{start:0, limit:50,userName:Ext.get('userName').dom.value}
				    });
				}},{xtype:'tbseparator'},
				{text:'添加用户',iconCls:'user_add',handler:function(){
					configFormWindow.show();
				}},{xtype:'tbseparator'},
				{text:'删除用户',iconCls:'user_delete',handler:function(){
					if( ds.getCount()==0 ) {
						Ext.MessageBox.alert('提示','无记录，无法删除！');
						return;
					}
					var records = sm.getSelections();
					if( records.length==0 ) {
						Ext.MessageBox.alert('提示','未选择记录，无法删除！');
						return;
					}
					Ext.MessageBox.confirm('确认对话框', '确认删除选中记录吗？', function(btn){
			    		if(btn=='yes'){
			    			delRecords(records);
			    		}
					});
				}},{xtype:'tbseparator'},
				{text:'保存修改',iconCls:'rec_save',handler:function(){
					if( ds.getCount()==0 ) {
						Ext.MessageBox.alert('提示','无记录，无法提交保存数据！');
						return;
					}
					var vRecords = ds.getModifiedRecords();
					if( vRecords.length==0 ){
						Ext.MessageBox.alert('提示','无修改记录，请修改数据后再点击保存！');
						return;
					}
					Ext.MessageBox.confirm('确认对话框', '确认保存提交修改的数据？', 
				    	function(btn){
				    		if(btn=='yes'){
				    			batchSaveRecord();
				    		}
						});
				}},{xtype:'tbseparator'},
				],
			bbar : new Ext.PagingToolbar({
				pageSize: 50,
				store: ds,
				displayInfo: true,
				displayMsg: '第{0} 到 {1} 条数据 共{2}条',
				emptyMsg: '未查询到资源'
			})
	});
	//加载数据
	ds.load({params:{start:0, limit:50}});
	ds.on('beforeload',function(){ 
	 		Ext.apply(this.baseParams,{userName:Ext.get('userName').dom.value}
	  	);
	});
}

// 创建活动内容面板
function createContentPanel(){
	this.contentPanel = new Ext.Panel({
		split : true,
		bodyStyle : "width:100%",
		region : 'center',
		layout:'fit',
		margins : '0 0 0 0',
		forceFit : true,
		stripeRows : true,
	    enableTextSelection : true 
	});
}

//页面初始化
function init(){
	// 创建对象
	this.createContentPanel();
	this.createGridPanel();
	this.contentPanel.add(this.gridPanel);
	//布局管理器
	this.createConfigFormWindow();
	this.createConfigFormPanel();
	this.configFormWindow.add(this.configFormPanel);
	
	this.viewport = new Ext.Viewport({
			layout:'border',
			border:true,
			items:[this.contentPanel]
	});
	this.viewport.render();
}

//创建用户窗口面板
function createConfigFormWindow(){
	configFormWindow = new Ext.Window({
				title : '添加用户信息',
				id : 'configFormWindow',
                layout:'fit',
                width:360,
                height:250,
                closeAction:'hide',
                plain: true,
                modal:true,
                collapsible: false,
                maximizable:false,
                draggable: true,
                closable: false,
                resizable:false,
                animateTarget:document.body
			});
}
//创建用户表单面板
function createConfigFormPanel(){
	configFormPanel = new Ext.FormPanel({
		labelWidth : 90,
		labelAlign:'right',
		id:'configFormPanel',
		frame : true,
		border:false,
		bodyStyle : 'padding:0px 0px 0',
		defaultType : 'textfield',
		items : [{
        	fieldLabel: '用户名',
		    name: 'userName',   
		    maxLength:'16',
			minLength:'6',
			width: 200,
			allowBlank: false,
            blankText: '用户名不能为空',
		    minLengthText: '用户名长度必须在6到16位之间',
		    maxLengthText: '用户名长度必须在6到16位之间'
   	 	},{
			allowBlank: false,  
		    name: 'password', 
		    inputType: 'password',
		    width: 200,
		    fieldLabel: '密码',
            blankText: '配置值不能为空'
   	 	},new Ext.form.ComboBox({
		    store: new Ext.data.SimpleStore({
			    fields: ['returnValue', 'displayValue'],
			    data : [['A','超级用户'], ['G','普通用户']]
			}),
		    displayField:'displayValue',
		    valueField:'returnValue',
		    typeAhead: true,
		    mode: 'local',
		    editable:false,
		    hiddenName:'type',
		    fieldLabel: '类型',
			width:100,
		    triggerAction: 'all',
		    emptyText:'全部',
		    selectOnFocus:true,
		    allowBlank: false, 
			name : 'type'
		}),{
   	 		width: 200,
			allowBlank: true,  
		    name: 'remark', 
		    fieldLabel: '备注描述'
   	 	}],
		buttons : [{
			text : '保存',
			handler:function(){
				var configForm = configFormPanel.getForm();
				if( configForm.isValid() ){
					saveAddConfig(configForm);
				}
			}
		}, {
			text : '取消',
			handler:function(){
				configFormWindow.hide();
			}
		}]
	});
}

function saveAddConfig(form){
	form.submit({
		url : '/sysuser/save',
		method : 'POST',
		success : function(from, action) {
			if( action.result.success ){
				configFormWindow.hide();
				configFormPanel.getForm().reset();
			}
			Ext.MessageBox.alert('提示框',action.result.respMsg);
			gridPanel.getStore().load({
				params:{start:0, limit:50}
			});
		},
		failure : processFailure,
		waitMsg : '正在保存数据，稍后...',
		waitTitle:'提示'
	});
}

//删除选中的
function delRecords(records){
	var ids = new Array();
	var index = 0;
	for( var i=0;i<records.length;i++ ){
		ids.push(records[i].get('id'));
	}
	if( ids.length==0 ){
		processFlag = false;
		return;
	}
	processFlag = true;
	this.showWaitingBar();
	Ext.Ajax.request({// 排列顺序
		url : systemContext + '/sysuser/delete',
		params : {
			userIds : ids
		},
		method : 'POST',
		success : function(response,action) {
			processFlag = false;
			var responseArray = Ext.util.JSON.decode(response.responseText);
			Ext.MessageBox.alert('提示框',responseArray.respMsg);
			gridPanel.getStore().load({
				params:{start:0, limit:50}
			});
		},
		failure : processFailure
	});
}

//批量保存数据
function batchSaveRecord(){
	var vRecords = gridPanel.getStore().getModifiedRecords(); //得到修改的数据（记录对象）
	var vCount = vRecords.length; //得到记录长度
	if (vCount > 0) {
        //begin 将记录对象转换为字符串（json格式的字符串）
        var vDatas = '[';
        for (var i = 0; i < vCount; i++) {
            vDatas += Ext.util.JSON.encode(vRecords[i].data) + ',';
        }
        vDatas = vDatas.substr(0, vDatas.length - 1) + ']';
        processFlag = true;
        this.showWaitingBar();
        Ext.Ajax.request({// 排列顺序
    		url : '/sysuser/batchRecords',
    		method : 'POST',
    		params: {datas: vDatas},
    		success : function(response,action) {
    			processFlag = false;
    			var responseArray = Ext.util.JSON.decode(response.responseText);
    			if( responseArray.respMsg!=null ){
    				Ext.MessageBox.alert('提示框',responseArray.respMsg);
    			}
    			if( responseArray.success){
    				gridPanel.getStore().commitChanges();
    				gridPanel.getStore().load({
    					params:{start:0, limit:50}
    				});
    			}
    		},
    		failure : processFailure
    	});
    }
}